package com.autobet.controller;

import com.alibaba.fastjson.JSONObject;
import com.autobet.dao.CommonDao;
import com.autobet.model.table.Account;
import com.autobet.services.*;
import com.autobet.utils.BetUtils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private CommonDao commonDao;
    @Autowired
    private BetService betService;
    @Autowired
    private ResultService resultService;

    public CommonController() {
    }

    @RequestMapping({"/index"})
    public String index(Model model) {
        try {
            model.addAttribute("envConfigService", new EnvConfigService());
        } catch (Exception var3) {
            ;
        }

        return "index";
    }

    @RequestMapping({"/createTable"})
    public String createTable(Model model) {
        try {
            this.commonDao.createTable();
        } catch (Exception var3) {
            model.addAttribute("message", "建表失败");
        }

        model.addAttribute("message", "建表成功");
        return "message";
    }

    @RequestMapping({"/test"})
    public String test(Model model) {
        try {
            Account account = new Account();
            account.setDataId("12");
            account.setAccountId("1232");
            account.setInsertDate(new Date());
            account.setRemark("测试");
            account.setPreAmount("1");
            this.commonDao.saveAccount(account);
        } catch (Exception var3) {
            model.addAttribute("message", "执行失败");
            return "message";
        }

        model.addAttribute("message", "执行成功");
        return "message";
    }

    @RequestMapping(
            value = {"/beginBet"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String beginBet(Model model) {
        try {
            this.betService.doBetBegin();
            return "{\"status\":\"success\"}";
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }
    }

    @RequestMapping({"/infoList"})
    public String getInfoList(Model model) {
        try {
            StringBuffer str = new StringBuffer();
            List<String> list = this.resultService.getInfoList();
            Iterator var4 = list.iterator();

            while(true) {
                if(!var4.hasNext()) {
                    model.addAttribute("infoList", str.toString());
                    break;
                }

                String info = (String)var4.next();
                str.append(info).append("\n");
            }
        } catch (Exception var6) {
            model.addAttribute("message", "执行失败！" + var6.getMessage());
            model.addAttribute("infoList", "");
            return "infoList";
        }

        model.addAttribute("message", "执行成功");
        return "infoList";
    }

    @RequestMapping(
            value = {"/stopSystem"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String stopSystem(Model model) {
        try {
            EnvConfigService.setTaskStatus("STOP");
            EnvConfigService.setWarningFlag("n");
            //更改开车设置
            for( int i= 1 ;i<= 10 ;i++){
                SetCarStatus.setCarStatus("dx" ,String.valueOf(i),true);
                SetCarStatus.setCarStatus("ds" ,String.valueOf(i),true);
            }
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }

        this.resultService.getInfoList().add("系统任务停止.......");
        return "{\"status\":\"success\"}";
    }

    @RequestMapping(
            value = {"/queryResult"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String queryResult( Model model) {
        try {
            StringBuffer infoBuffer = new StringBuffer();
            infoBuffer.append("{\"status\":\"success\",\"list\":[");
            List<String> infolist = this.resultService.queryResultHis();
            if(infolist != null && infolist.size() != 0) {
                Iterator var5 = infolist.iterator();

                while(var5.hasNext()) {
                    String into = (String)var5.next();
                    infoBuffer.append("{\"message\":\"").append(into).append("\"},");
                }

                infoBuffer.deleteCharAt(infoBuffer.lastIndexOf(","));
                infoBuffer.append("]}");
                return infoBuffer.toString();
            } else {
                return "{\"status\":\"success\",\"list\":[{\"message\":\"数据库无记录\"}]}";
            }
        } catch (Exception var7) {
            return "{\"status\":\"failed\",\"message\":\"" + var7.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/querySystemInfoJson"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String querySystemInfoJson(HttpServletRequest request, HttpServletResponse response) {
        StringBuffer json = new StringBuffer();

        try {
            List<String> list = this.resultService.getInfoList();
            if(list != null && list.size() != 0) {
                json.append("{\"status\":\"success\",\"list\":[");

                for(int i = list.size() - 1; i > 0; --i) {
                    String info = (String)list.get(i);
                    json.append("{\"message\":\"").append(info).append("\"},");
                }

                json.deleteCharAt(json.lastIndexOf(","));
                json.append("]}");
                return json.toString();
            } else {
                json.append("{\"status\":\"success\",\"list\":[]}");
                return json.toString();
            }
        } catch (Exception var7) {
            json = new StringBuffer();
            json.append("{\"status\":\"failed\",\"message\":\"").append(var7.getMessage()).append("\"}");
            return json.toString();
        }
    }

    @RequestMapping(
            value = {"/initSystemParaAndBeginBet"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String initSystemParaAndBeginBet(@RequestParam String accountId, @RequestParam String cookie, @RequestParam String queryResultIntervalTime, @RequestParam String queryBetUrl,
                                            @RequestParam String selectPeriod,@RequestParam String searchDate) {
        try {
            if("RUNING".equals(EnvConfigService.getTaskStatus())) {
                throw new Exception("系统正在执行中，请停止任务后再执行下单操作");
            } else if(!accountId.isEmpty() && !queryResultIntervalTime.isEmpty() && !queryBetUrl.isEmpty()) {
                EnvConfigService.setCookie(cookie);
                EnvConfigService.cookie = cookie;
                EnvConfigService.setAccountId(accountId);
                EnvConfigService.setQueryResultIntervalTime(queryResultIntervalTime);
                EnvConfigService.setQueryBetUrl(queryBetUrl);
                EnvConfigService.selectPeriod = selectPeriod;
                EnvConfigService.setSearchDate(searchDate);
                this.betService.doBetBeginEntry("both");
                return "{\"status\":\"success\"}";
            } else {
                throw new Exception("系统参数存在空值！");
            }
        } catch (Exception var14) {
            log.error("err!", var14);
            this.resultService.getInfoList().add("系统启动异常[" + var14.getMessage() + "]");
            return "{\"status\":\"failed\",\"message\":\"" + var14.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/resultHis"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String resultHis(HttpServletRequest request) {
        try {
            this.resultService.resultHis();
            return "{\"status\":\"success\"}";
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/repairResultHis"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String repairResultHis(HttpServletRequest request) {
        try {
            this.betService.repairBetData(BetUtils.getCurrDateYYYYMMDD(), "581878", "dx");
            return "{\"status\":\"success\"}";
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/queryMoneytake"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String queryMoneytake(HttpServletRequest request) {
        try {
            BigDecimal allmoneytake = this.commonDao.queryAutoHisBuymoneytakeAll("both");
            BigDecimal allRealMoneytake = this.commonDao.queryAutoHisBuymoneytakeRealAll("both");
            BigDecimal allmoneytakeByDate = this.commonDao.queryAllAutoHisBuymoneytakeByResultDate(BetUtils.getCurrDateYYYYMMDD(), "both");
            BigDecimal allRealMoneytakeByDate = this.commonDao.queryRealAutoHisBuymoneytakeByResultDateAndSimulateFlag("n", BetUtils.getCurrDateYYYYMMDD(), "both");
            Map<String, String> jsonMap = new HashMap();
            jsonMap.put("status", "success");
            jsonMap.put("allmoneytake", allmoneytake.toString());
            jsonMap.put("allRealMoneytake", allRealMoneytake.toString());
            jsonMap.put("allmoneytakeByDate", allmoneytakeByDate.toString());
            jsonMap.put("allRealMoneytakeByDate", allRealMoneytakeByDate.toString());
            return JSONObject.toJSONString(jsonMap);
        } catch (Exception var7) {
            return "{\"status\":\"failed\",\"message\":\"" + var7.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/clearInfo"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String clearInfo(HttpServletRequest request) {
        try {
            this.resultService.getInfoList().clear();
            return "{\"status\":\"success\"}";
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/querywarning"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String querywarning(HttpServletRequest request) {
        try {
            return "y".equals(EnvConfigService.getWarningFlag())?"{\"status\":\"success\"}":"{\"status\":\"failed\"}";
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/setPara"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String setPara(@RequestParam String para) {
        try {
            JSONObject jsonobj = JSONObject.parseObject(para);
            String cutLostAmount = jsonobj.getString("cutLostAmount");
            String cutWinAmount = jsonobj.getString("cutWinAmount");
            String realBetFlag = jsonobj.getString("realBetFlag");
            String cutDieFlag = jsonobj.getString("cutDieFlag");
            String cutLostAmountFlag = jsonobj.getString("cutLostAmountFlag");
            String cutWinFlag = jsonobj.getString("cutWinFlag");
            String dieCount = jsonobj.getString("dieCount");
            EnvConfigService.setCutDieFlag(cutDieFlag);
            EnvConfigService.setCutLostAmount(cutLostAmount);
            EnvConfigService.setCutWinAmount(cutWinAmount);
            EnvConfigService.setRealBetFlag(realBetFlag);
            EnvConfigService.setCutLostAmountFlag(cutLostAmountFlag);
            EnvConfigService.setCutWinFlag(cutWinFlag);
            EnvConfigService.setDieCount(dieCount);
            return "{\"status\":\"success\"}";
        } catch (Exception var10) {
            return "{\"status\":\"failed\",\"message\":\"" + var10.getMessage() + "\"}";
        }
    }

    @RequestMapping(
            value = {"/payload"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String payload(HttpServletRequest request) {
        try {
            StringBuilder stringBuilder = new StringBuilder();
            InputStream inputStream = request.getInputStream();
            BufferedReader bufferedReader = null;
            if(inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                boolean var6 = true;

                int bytesRead;
                while((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }

            return "{\"status\":\"success\",\"message\":\"" + stringBuilder.toString() + "\"}";
        } catch (Exception var7) {
            return "{\"status\":\"failed\",\"message\":\"" + var7.getMessage() + "\"}";
        }
    }


    /**
     * 设置真实下注
     * @return
     */
    @RequestMapping(
            value = {"/setRealBetFlag"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String setRealBetFlag() {
        try {
            if(EnvConfigService.realBetFlag.equals("y")){
                EnvConfigService.realBetFlag = "n";
            }else if(EnvConfigService.realBetFlag.equals("n")){
                EnvConfigService.realBetFlag = "y";
            }
            return "{\"status\":\"success\",\"message\":\"真实下注\",\"data\":\"" + EnvConfigService.realBetFlag + "\"}";
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }
    }

    /**
     * 获取真实下注状态
     * @return
     */
    @RequestMapping(
            value = {"/getRealBetFlag"},
            produces = {"application/json;charset=UTF-8"}
    )
    @ResponseBody
    public String getRealBetFlag() {
        try {

            return "{\"status\":\"success\",\"message\":\"真实下注\",\"data\":\"" + EnvConfigService.realBetFlag + "\"}";
        } catch (Exception var3) {
            return "{\"status\":\"failed\",\"message\":\"" + var3.getMessage() + "\"}";
        }
    }


}
